package com.heima.kafka;

import org.apache.kafka.clients.producer.*;
import org.junit.Test;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class ProducerQuickStart {
    @Test
    public void sendMsg() throws ExecutionException, InterruptedException {
        // 1.配置kafka
        Properties properties = new Properties();

        // 配置kafka连接地址
        properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");

        // 配置消息key的序列化器
        properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");

        // 配置消息value的序列化器
        properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");

        // 发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);

        // 配置消息确认机制
        properties.put(ProducerConfig.ACKS_CONFIG,"1"); //默认的也是1

        // 配置数据压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"lz4");

        // 2.创建生产者
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        // 封装发送消息
        ProducerRecord<String, String> record = new ProducerRecord<>
                ("itheima-topic","100001","hello kafka");
        // 3.发送消息
        // 同步发送
       /* RecordMetadata recordMetadata = producer.send(record).get();
        System.out.println(recordMetadata);*/

        // 异步发送
        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata metadata, Exception e) {
                if (e != null){
                    System.out.println("记录异常信息到日志表中");
                }
                System.out.println(metadata.offset());
            }
        });

        // 4.关闭kafka
        producer.close();
    }
}
